package com.miqtech.master.wyrecorder.screenrecorder.services;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.projection.MediaProjection;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.miqtech.master.wyrecorder.R;
import com.miqtech.master.wyrecorder.ui.ScreenRecorderActivity;
import com.miqtech.master.wyrecorder.utils.DeviceUtils;
import com.miqtech.master.wyrecorder.utils.L;
import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;
import pushengine.YuerPublisher;

public class PushStreamService extends Service implements YuerPublisher.YuerPublisherListener {
    private static final String TAG = "PushStreamService";
    final int MSG_CREATEFLOAT = 0X006;
    final int MSG_CREATECHAT = 0X004;
    RelativeLayout mFloatLayout;
    private Timer mTimer = null;
    private MyTimerTask mTimerTask;
    private long mills = 0;
	private WeakReference<PushStreamServiceListener> mWeakUIListener;
    private String mPushUrl = null;
    private WindowManager wm;
    private WindowManager.LayoutParams wmLayoutParams;
    private int mStatusHeight = 0;
    private RelativeLayout mFloatLayoutChat;
    private WindowManager.LayoutParams wnLayoutParamsChat;
    private TextView tvChatInfo;
    private YuerPublisher mPublisher;
    private boolean hideChatFloat;

    Handler mHandle = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_CREATEFLOAT:
                    createFloatActionButton();
                    break;
                case MSG_CREATECHAT:
                    createFloatChatView();
                    break;
            }
        }
    };
    public PushStreamService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new PushStreamBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (wm == null) {
            wm = (WindowManager) getApplication().getSystemService(WINDOW_SERVICE);
        }
        if (mFloatLayout != null) {
            wm.removeView(mFloatLayout);
            mFloatLayout = null;
        }
        if (mFloatLayoutChat != null) {
            wm.removeView(mFloatLayoutChat);
            mFloatLayoutChat = null;
        }
        if(mPublisher == null){
			int mVideoEncodeQuality = YuerPublisher.YuerVideoEncodeQuality.VIDEO_ENCODE_QUALITY_NONE;
			mPublisher = new YuerPublisher(mVideoEncodeQuality);
			mPublisher.setListener(this);
        }

        Notification.Builder builder = new Notification.Builder(this);
        builder.setAutoCancel(false);
        builder.setPriority(Notification.PRIORITY_MAX);
        Intent notifyIntent = new Intent(this, ScreenRecorderActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        Notification notification = builder.build();
        notification.flags = Notification.FLAG_NO_CLEAR;
        startForeground(1001, new Notification());
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopPushStream();
        stopService();
    }

    public void stopService() {
        stopSelf();
    }
	
    private void startTimer(){
		stopTimer();
        if (mTimer == null) {
            mTimer = new Timer();
        }

        if (mTimerTask == null) {
            mTimerTask = new MyTimerTask(PushStreamService.this);
        }
        if(mTimer != null && mTimerTask != null )
            mTimer.schedule(mTimerTask, 0, 1000);

    }

    private void stopTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }
	
	@Override
    public void onPublishStart(){
		PushStreamServiceListener mListener= mWeakUIListener.get();
		if(mListener != null){
			mListener.onLiveStarted();
		}
		if(mHandle != null){
			mHandle.sendEmptyMessage(MSG_CREATEFLOAT);
			mHandle.sendEmptyMessage(MSG_CREATECHAT);
		}
		startTimer();
	}
	
	@Override
    public void onPublishStop(){
        stopTimer();
	}

    @Override
    public void onPublishException() {
        Log.e(TAG, "onRtmpException");
		stopTimer();
        if (mPublisher != null) {
            mPublisher.stopPublish();
			mPublisher = null;
        }
		PushStreamServiceListener mListener= mWeakUIListener.get();
		if(mListener != null){
			mListener.onLiveError();
		}
    }

    public void startPushStream() {
		Log.e(TAG, "startPushStream()");
		if(mPublisher != null){
		    mPublisher.startPublish(mPushUrl,false);
		}
		Log.e(TAG, "startPushStream()1111");
    }
    public void stopPushStream() {
		Log.e(TAG, "stopPushStream()");
		stopTimer();
		mills = 0;
        if(mPublisher != null){
			mPublisher.stopPublish();
		}		
        if (mHandle != null) {
            mHandle.removeCallbacksAndMessages(null);
            mHandle = null;
        }
        removeFloatView();
        removeFloatChatView();
    }
    public void setPushStreamParams(MediaProjection mediaProjection, int videoWidth, int videoHeight, int densityDpi, String pushUrl, int statusHeight) {
		Log.e(TAG, "videoWidth = "+videoWidth+" videoHeight = "+videoHeight);
        if(mPublisher != null){
			mPublisher.setScreenCaptureParameter(mediaProjection,densityDpi,videoWidth,videoHeight);
		}	
        mPushUrl = pushUrl;
        mStatusHeight = statusHeight;
    }
    public long getPushStreamTimes() {
        return mills;
    }
	
	public void setListener(PushStreamServiceListener listener){
		mWeakUIListener = new WeakReference<PushStreamServiceListener>(listener);
	}
    public void mute(boolean isMute){
		if(mPublisher != null){
			mPublisher.mute(isMute);
		}
	}
    public interface PushStreamServiceListener {
        void onLiveStarted();
        void onLiveError();
        void updateTime();
    }



    /**
     * 创建悬浮球
     */
    private void createFloatActionButton() {
        if (mFloatLayout != null && mFloatLayout.getVisibility() == View.VISIBLE) {
            return;
        }
        wmLayoutParams = new WindowManager.LayoutParams();
        wmLayoutParams.type = WindowManager.LayoutParams.TYPE_TOAST;
        wmLayoutParams.format = PixelFormat.RGBA_8888;
        wmLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;

        wmLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        wmLayoutParams.x = DeviceUtils.deviceWidth(this);
        wmLayoutParams.y = DeviceUtils.deviceHeight(this) / 2;
        wmLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        final LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
        mFloatLayout = (RelativeLayout) inflater.inflate(R.layout.layout_live_float, null);
        wm.addView(mFloatLayout, wmLayoutParams);

        final ImageView imageButton = (ImageView) mFloatLayout.findViewById(R.id.float_id);
        mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        imageButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    int x = DeviceUtils.deviceWidth(PushStreamService.this) - imageButton.getMeasuredWidth() / 2;
                    wmLayoutParams.x = event.getRawX() > x / 2 ? x : 0;
                    wmLayoutParams.y = (int) event.getRawY() - imageButton.getMeasuredHeight() / 2 - mStatusHeight;
                    wm.updateViewLayout(mFloatLayout, wmLayoutParams);
                } else {
                    wmLayoutParams.x = (int) event.getRawX() - imageButton.getMeasuredWidth() / 2;
                    wmLayoutParams.y = (int) event.getRawY() - imageButton.getMeasuredHeight() / 2 - mStatusHeight;
                    wm.updateViewLayout(mFloatLayout, wmLayoutParams);
                }
                return false;
            }
        });
        imageButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // hide the button
                if (mFloatLayout.findViewById(R.id.ll_hidden).getVisibility() == View.GONE) {
                    mFloatLayout.findViewById(R.id.ll_hidden).setVisibility(View.VISIBLE);
                    imageButton.setVisibility(View.GONE);
                }
            }
        });


        mFloatLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mFloatLayout != null && mFloatLayout.findViewById(R.id.ll_hidden).getVisibility() == View.VISIBLE) {
                    mFloatLayout.findViewById(R.id.ll_hidden).setVisibility(View.GONE);
                    imageButton.setVisibility(View.VISIBLE);
                }
                return false;
            }
        });
        final ImageView home = (ImageView) mFloatLayout.findViewById(R.id.img_home);
        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = null;
            /*
            if (mActivity == null) {
				intent = new Intent(mPushStreamService.this, ScreenRecorderActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
			} else */
                {
                    intent = new Intent(PushStreamService.this, ScreenRecorderActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
                mFloatLayout.findViewById(R.id.ll_hidden).setVisibility(View.GONE);
                imageButton.setVisibility(View.VISIBLE);
            }
        });

        final ImageView chat = (ImageView) mFloatLayout.findViewById(R.id.img_chat);
        chat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideChatFloat = !hideChatFloat;
                if (hideChatFloat) {
                    mFloatLayoutChat.setVisibility(View.GONE);
                    chat.setImageResource(R.drawable.icon_float_chat_close);
                } else {
                    mFloatLayoutChat.setVisibility(View.VISIBLE);
                    chat.setImageResource(R.drawable.icon_float_chat_open);
                }
            }
        });
        mFloatLayout.setVisibility(View.GONE);
    }

    private void createFloatChatView() {
        if (mFloatLayoutChat != null && mFloatLayoutChat.getVisibility() == View.VISIBLE) {
            return;
        }
        wnLayoutParamsChat = new WindowManager.LayoutParams();
        wnLayoutParamsChat.type = WindowManager.LayoutParams.TYPE_TOAST;
        wnLayoutParamsChat.format = PixelFormat.RGBA_8888;
        wnLayoutParamsChat.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;

        wnLayoutParamsChat.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
        wnLayoutParamsChat.y = 0;
        wnLayoutParamsChat.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wnLayoutParamsChat.height = WindowManager.LayoutParams.WRAP_CONTENT;
        final LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
        mFloatLayoutChat = (RelativeLayout) inflater.inflate(R.layout.layout_live_chat_float, null);
        wm.addView(mFloatLayoutChat, wnLayoutParamsChat);

        final RelativeLayout rlParentChat = (RelativeLayout) mFloatLayoutChat.findViewById(R.id.rlParentChat);
        tvChatInfo = (TextView) mFloatLayoutChat.findViewById(R.id.tvChatInfo);
        mFloatLayoutChat.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        rlParentChat.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getRawX() != 0 && event.getRawY() != 0) {
                    wnLayoutParamsChat.x = (int) event.getRawX() - rlParentChat.getMeasuredWidth() / 2;
                    wnLayoutParamsChat.y = (int) event.getRawY() - rlParentChat.getMeasuredHeight() / 2 - mStatusHeight;
                    if (mFloatLayoutChat != null) {
                        wm.updateViewLayout(mFloatLayoutChat, wnLayoutParamsChat);
                    }
                }
                L.e(TAG, event.getRawX() + ":::" + event.getRawY() + ":::" + wnLayoutParamsChat.x + ":::" + wnLayoutParamsChat.y);
                return true;
            }

        });
        setFloatChatViewVisible(false);
    }

    public TextView getFloatTextView() {
        if (tvChatInfo != null) {
            return tvChatInfo;
        }
        return null;
    }

    private void removeFloatView() {
        if (wm != null && mFloatLayout != null && mFloatLayout.isShown()) {
            wm.removeView(mFloatLayout);
            mFloatLayout = null;
        }
    }

    private void removeFloatChatView() {
        if (wm != null && mFloatLayoutChat != null && mFloatLayoutChat.isShown()) {
            wm.removeView(mFloatLayoutChat);
            mFloatLayoutChat = null;
        }
    }

    public void setFloatChatViewVisible(boolean isVisible) {
        if (mFloatLayoutChat == null) {
            return;
        }
        mFloatLayoutChat.setVisibility(!hideChatFloat && isVisible ? View.VISIBLE : View.GONE);
    }

    public void showFloatActionButton(boolean mShow) {
        if (mFloatLayout != null) {
            if (mShow) {
                mFloatLayout.setVisibility(View.VISIBLE);
            } else {
                mFloatLayout.setVisibility(View.GONE);
            }
        }
    }
    public static class MyTimerTask extends TimerTask {
        private WeakReference<PushStreamService> pushStreamServiceWeakReference;
        public MyTimerTask(PushStreamService pushStreamService) {
            pushStreamServiceWeakReference = new WeakReference<PushStreamService>(pushStreamService);
        }

        @Override
        public void run() {
            PushStreamService mPushStreamService = pushStreamServiceWeakReference.get();
            if (mPushStreamService != null) {
               mPushStreamService.mills += 1000;
			   if(mPushStreamService.mWeakUIListener.get() != null){
			       mPushStreamService.mWeakUIListener.get().updateTime();
			   }
            }
        }

    }

    public class PushStreamBinder extends Binder {
        public PushStreamService getService() {
            return PushStreamService.this;
        }
    }
}